package br.unifor.cct.mia.util;

import java.io.File;
import java.io.IOException;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MetaEventListener;
import javax.sound.midi.MetaMessage;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.Transmitter;

public class Sound {

	private static Sequencer sm_sequencer = null;
	private static Synthesizer sm_synthesizer = null;

	public static void playSound(String file) {
		if (file==null) file = "E:\\Pedro\\workspace\\AGMining\\src\\simp.mid";
		String strFilename = file;
		File midiFile = new File(strFilename);

		Sequence sequence = null;
		try {
			sequence = MidiSystem.getSequence(midiFile);
			sm_sequencer = MidiSystem.getSequencer();

			sm_sequencer.addMetaEventListener(new MetaEventListener() {
				public void meta(MetaMessage event) {
					if (event.getType() == 47) {
						sm_sequencer.close();
						if (sm_synthesizer != null) {
							sm_synthesizer.close();
						}
					}
				}
			});

			sm_sequencer.open();
			sm_sequencer.setSequence(sequence);

			if (!(sm_sequencer instanceof Synthesizer)) {
				try {
					sm_synthesizer = MidiSystem.getSynthesizer();
					sm_synthesizer.open();
					Receiver synthReceiver = sm_synthesizer.getReceiver();
					Transmitter seqTransmitter = sm_sequencer.getTransmitter();
					seqTransmitter.setReceiver(synthReceiver);
				} catch (MidiUnavailableException e) {
					e.printStackTrace();
				}
			}
			sm_sequencer.start();
		} catch (InvalidMidiDataException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MidiUnavailableException e) {
			e.printStackTrace();
		}
	}
}
